import time
from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from service.close_element import closed


def open_windows():
    """
    daemon模式启动Chrome浏览器
    :return:
    """
    url = "https://www.zhipin.com/web/user/?ka=header-login"

    # 设置ChromeOptions
    options = Options()
    options.add_argument('--ignore-certificate-errors')  # 忽略SSL错误
    options.add_argument('--ignore-ssl-errors')  # 忽略SSL错误
    options.set_capability('goog:loggingPrefs', {'performance': 'ALL'})
    options.add_experimental_option('excludeSwitches', ['enable-automation'])
    options.add_argument('--disable-blink-features=AutomationControlled')

    # 设置ChromeDriver的路径
    # t = r'./chromedriver.exe'
    # service = ChromeService(executable_path=t)
    service = ChromeService()

    # 启动Chrome浏览器
    browser = webdriver.Chrome(service=service, options=options)

    browser.get(url)
    browser.maximize_window()
    WebDriverWait(browser, 10).until(  # 使用显性等待
        EC.presence_of_element_located((By.TAG_NAME, "body"))  # 等待页面加载
    )
    check_login_status(browser)
    time.sleep(3.5)

    print("关闭弹窗1")
    closed(browser)
    print("关闭弹窗2")

    return browser


def check_login_status(browser):
    """
    等待登录成功
    :return:
    """
    while True:
        if is_logged_in(browser):
            print("登录成功")
            time.sleep(5)
            break
        else:
            print("未登录，继续检查...")
        time.sleep(2)


def is_logged_in(browser):
    """
    检测登录状态
    :return:
    """
    try:
        # 方法1：检查URL是否变化
        current_url = browser.current_url
        if "web/chat/index" in current_url:  # 替换为实际登录成功后的URL
            return True

        # # 方法2：检查特定元素
        # wait = WebDriverWait(self.browser, 10)
        # welcome_element = wait.until(
        #     EC.presence_of_element_located((By.XPATH, "//div[contains(text(),'首页')]")))  # 替换为实际首页信息的XPath
        # return welcome_element is not None

    except Exception as e:
        print(f"检查登录状态时发生错误: {e}")
        raise e